package com.tgy.controller;

import com.tgy.dao.DepartmentDao;
import com.tgy.dao.EmployeeDao;
import com.tgy.entity.Department;
import com.tgy.entity.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Collection;

/***
 * @ClassName: IndexController
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 12:33 2021/12/27
 * @version : V1.0
 */
@Controller
public class LoginController {

    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model, HttpSession session){
        if(!StringUtils.isEmpty(username) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else{
            model.addAttribute("msg","用户名或密码错误");
            return "index";
        }

    }

    @Resource
    EmployeeDao employeeDao;
    @Resource
    DepartmentDao departmentDao;
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }
    @GetMapping("emp")
    public String toAdd(Model model){
        Collection<Department> departments = departmentDao.getAll();
        model.addAttribute("departments",departments);
        return "emp/add";
    }
    @PostMapping("emp")
    public String add(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    @GetMapping("toUpdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("employee",employee);
        Collection<Department> all = this.departmentDao.getAll();
        model.addAttribute("departments",all);
        return "emp/update";
    }


    @PostMapping("updateUser")
    public String update(Employee employee){
        employeeDao.save(employee);
        return "redirect/emps";
    }
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }


}
